package com.ruoyi.web.zbAdmin.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import com.mongodb.client.result.UpdateResult;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.web.zbAdmin.controller.param.BaseUserQuery;
import com.ruoyi.web.zbAdmin.domain.CaiBaseUser;
import com.ruoyi.web.zbAdmin.mapper.CaiBaseUserMapper;
import com.ruoyi.web.zbAdmin.utils.genID.IDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags="才能招标-用户信息管理")
@RestController
@RequestMapping("/zbApi/user")
@Slf4j
public class CaiUserBaseController extends BaseController {

    @Autowired
    private CaiBaseUserMapper userMapper;

    public static final String collectionName = "cai_base_user";

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public TableDataInfo list(BaseUserQuery userQuery) {

        log.info("=====>"+JSONUtil.toJsonStr(userQuery));
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();

        Query query = new Query();
        if(StrUtil.isNotBlank(userQuery.getPhone())){
            query.addCriteria(Criteria.where("phone").is(userQuery.getPhone()));
        }
        // 设置起始页和每页查询条数
        Pageable pageable = PageRequest.of(userQuery.getCurPage(), userQuery.getPageSize(), Sort.by(Sort.Order.desc("id")));
        // 查询记录总数
        long totalCount = mongoTemplate.count(query,collectionName);
        //查询分页后的记录
        List<CaiBaseUser> result = mongoTemplate.find(query.with(pageable), CaiBaseUser.class, collectionName);

        return TableDataInfo.success(result,totalCount);
    }




    @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
    @GetMapping("/{userId}")
    public AjaxResult getById(@PathVariable String userId) {
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        CaiBaseUser user = mongoTemplate.findById(userId,CaiBaseUser.class,collectionName);
        if(user==null){
            return AjaxResult.error("用户不存在!");
        }
        user.setPassword(null); //不要显示密码
        return AjaxResult.success("成功",user);
    }

    @ApiOperation("新增用户")
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
    })*/
    @PostMapping("/save")
    public AjaxResult save(CaiBaseUser user) {


        user.setId(IDUtils.getID());
        user.setPassword(Md5Utils.hash(user.getPassword()));
        this.userMapper.insert(user);

        return AjaxResult.success("保存成功");
    }

    @ApiOperation("更新用户")
    @PostMapping("/update")
    public AjaxResult update(CaiBaseUser user) {
        log.info("===>"+JSONUtil.toJsonStr(user));
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getId())) {
            return AjaxResult.success("ID为空");
        }
        Update update = new Update();
        update.set("showName",user.getShowName());
        if(StrUtil.isNotBlank(user.getPassword())) {
            update.set("password",Md5Utils.hash(user.getPassword()));
        }
        update.set("phone",user.getPhone());
        update.set("email",user.getEmail());
        update.set("vipEndTime",user.getVipEndTime());
        update.set("delFlag",user.getDelFlag());
        UpdateResult re = this.userMapper.getMongoTemplate().upsert(Query.query(Criteria.where("id").is(user.getId())),update,collectionName);

        return AjaxResult.success("修改成功",re.getMatchedCount());


    }

    @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "userId", value = "用户ID",required = true)
    @PostMapping("/delete/{userId}")
    public AjaxResult delete(@PathVariable String userId) {

        UpdateResult result=this.userMapper.getMongoTemplate().upsert(Query.query(Criteria.where("_id").is(userId)), Update.update("delFlag",CaiBaseUser.IS_DEL_YES),collectionName);

        return AjaxResult.success("删除成功",result.getMatchedCount());

    }



    public static void main(String[] args) {
        System.out.println(MD5.create().digestHex("newability2021"));
    }
}
